package asyncTasks;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import basicClasses.PlaceSearchResult;

import android.os.AsyncTask;
import android.util.Log;


public class AutocompleteResults extends AsyncTask<String, Void, ArrayList<PlaceSearchResult>> {

	PlaceSearchResult result = new PlaceSearchResult();
	ArrayList<PlaceSearchResult> list;
	
	@Override
	protected ArrayList<PlaceSearchResult> doInBackground(String... params) {
		
		ArrayList<String> resultList = null;
		list = new ArrayList<PlaceSearchResult>();
		
		HttpURLConnection conn = null;
		StringBuilder jsonResults = new StringBuilder();
		try{
			StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/autocomplete/json");
			sb.append("?sensor=false");
			sb.append("&key=AIzaSyDspt3tRVqb0O0QhXhyn07AiVFWiB0mF40");
			sb.append("&components=country:us");
			sb.append("&input=" + URLEncoder.encode(params[0], "utf8"));
			
			URL url = new URL(sb.toString());
	        conn = (HttpURLConnection) url.openConnection();
	        InputStreamReader in = new InputStreamReader(conn.getInputStream());
	        
	     // Load the results into a StringBuilder
	        int read;
	        char[] buff = new char[1024];
	        while ((read = in.read(buff)) != -1) {
	            jsonResults.append(buff, 0, read);
	        }
	    } catch (MalformedURLException e) {
	        Log.e("AutoComplete", "Error processing Places API URL", e);
	        return null;
	    } catch (IOException e) {
	        Log.e("AutoComplete", "Error connecting to Places API", e);
	        return null;
	    } finally {
	        if (conn != null) {
	            conn.disconnect();
	        }
	    }
		
		 try {
		        // Create a JSON object hierarchy from the results
		        JSONObject jsonObj = new JSONObject(jsonResults.toString());
		        JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
		        
		        
		        // Extract the Place descriptions from the results
		        //resultList = new ArrayList<String>(predsJsonArray.length());
		        for (int i = 0; i < predsJsonArray.length(); i++) {
		        	result = new PlaceSearchResult();
		            result.description = predsJsonArray.getJSONObject(i).getString("description");
		            result.reference = predsJsonArray.getJSONObject(i).getString("reference");
		            result.id = predsJsonArray.getJSONObject(i).getString("id");
		            list.add(result);
		        }
		
		    } catch (JSONException e) {
		        Log.e("AutoComplete", "Cannot process JSON results", e);
		    }
		return list;
	}

}
